package com.deep.spring.v9.service.impl;

import com.deep.spring.v9.model.User;
import com.deep.spring.v9.service.ICacheService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 若未配置@CacheConfig(cacheNames = "hello"), 则@Cacheable一定要配置value
 * 若@CacheConfig(cacheNames = "hello") 与 @Cacheable(value = "123")都配置了， 则@Cacheable(value = "123") 生效
 * <p>
 * 当然@CacheConfig还有一些其他的配置项，Cacheable也有一些其他的配置项
 */
@Service
public class CacheServiceImpl implements ICacheService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    @Cacheable(value = "test", key = "targetClass + '_' + methodName")
    public String getName() {
        System.out.println("getName, no cache now...");
        return "brucelee";
    }

    @Override
    @Cacheable(value = "user", key = "targetClass + ':' + methodName + '_' + #p0", unless = "#result.size() <= 0")
    public List<User> listUser(int pageNum, int pageSize) {
        System.out.println("listUser no cache now...");
        List<User> users = new ArrayList<>();
        users.add(new User("zhengsan", 22));
        users.add(new User("lisi", 20));
        return users;
    }

    /**
     * 缓存不是缓存管理器管理，那么不受缓存管理器的约束
     * 缓存管理器中的配置不适用与此
     * 这里相当于我们平时直接通过redis-cli操作redis
     *
     * @return
     */
    @Override
    public String getUserName() {

        String userName = redisTemplate.opsForValue().get("userName");
        if (StringUtils.isNotEmpty(userName)) {
            return userName;
        }

        System.out.println("getUserName, no cache now...");
        redisTemplate.opsForValue().set("userName", "userName");
        return "userName";
    }

}
